/******************************************************************************
 * @File name   :      IDealerUsrGrpApprovalServiceImpl.java
 *
 * @Author      :      chen shixiang
 *
 * @Date        :      2011-6-7
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-7 下午12:30:38        chen shixiang     1.0            Initial Version
 * 2011-9-29 下午02:48:32 HeHao       1.1             Change Method createUserAccountToGDMS
 * 2011-9-29 下午03:17:54 HeHao       1.2             Change Method setValue
 * 2011-10-10          tun.tan     2.0           throw exception with error code constant
 * 2011-10-19 下午02:47:22 wangzhize       1.2        employeeinfo int to Integer ,fix type mismatch error
 * 2011-10-21 下午02:18:41    HeHao        1.3        Change Method transferUserDate
 * 2011-10-31 下午03:41:21    HeHao        1.4        Modify Method approveUserGroupApplication
 * 2011-10-31 下午05:24:01        HeHao           1.5             Add Method autoApproveUserGroupApplication
 * 2011-12-05 下午04:57:06        caijunyi       1.6          fix unregister app
 *****************************************************************************/
package com.cap.bts.framework.dm.approval.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.ge.dealer.dao.IDealerDao;
import com.cap.bts.commonfunc.ge.dealer.domain.DealerInfo;
import com.cap.bts.commonfunc.ge.dealer.service.IDealerService;
import com.cap.bts.framework.approvalrule.constants.ApplicationState;
import com.cap.bts.framework.approvalrule.constants.ApplicationTypeConstants;
import com.cap.bts.framework.approvalrule.constants.ApprovalResult;
import com.cap.bts.framework.approvalrule.dao.IApplicationRuleStepDao;
import com.cap.bts.framework.approvalrule.domain.ApplicationApproval;
import com.cap.bts.framework.approvalrule.domain.ApplicationRuleStep;
import com.cap.bts.framework.approvalrule.service.IApplicationApprovalService;
import com.cap.bts.framework.approvalrule.service.IApprovalRuleService;
import com.cap.bts.framework.codemapping.dto.CodeInfoDto;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.BrandConstants;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.ApplicationContextUtil;
import com.cap.bts.framework.common.util.CodeTextUtils;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.dm.approval.dao.IDealerUsrGrpApprovalDao;
import com.cap.bts.framework.dm.approval.domain.UserGroupApplication;
import com.cap.bts.framework.dm.approval.dto.ApplicationResultDto;
import com.cap.bts.framework.dm.approval.dto.ApprovalSubmitDto;
import com.cap.bts.framework.dm.approval.dto.MultiApprovalSubmitDto;
import com.cap.bts.framework.dm.approval.dto.QueryApplicationDto;
import com.cap.bts.framework.dm.approval.dto.UnregisterUserApplicationDto;
import com.cap.bts.framework.dm.approval.dto.UserAccountApprovalDto;
import com.cap.bts.framework.dm.approval.service.IDealerUsrGrpApprovalService;
import com.cap.bts.framework.dm.employeemgnt.constants.EmployeeUserAccountConstants;
import com.cap.bts.framework.dm.employeemgnt.service.IMaintainDealerEmployeeService;
import com.cap.bts.framework.paramgnt.constant.SystemParamConstants;
import com.cap.bts.framework.paramgnt.service.ISystemParaManagement;
import com.cap.bts.framework.usermgnt.constant.EmployeeStatus;
import com.cap.bts.framework.usermgnt.constant.OrganizationType;
import com.cap.bts.framework.usermgnt.constant.UserGroupCode;
import com.cap.bts.framework.usermgnt.constant.UserStatus;
import com.cap.bts.framework.usermgnt.constant.UserType;
import com.cap.bts.framework.usermgnt.dao.IEmployeeInfoDao;
import com.cap.bts.framework.usermgnt.dao.IOrganizationDao;
import com.cap.bts.framework.usermgnt.dao.IOrganizationUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupDao;
import com.cap.bts.framework.usermgnt.dao.IUserUsrGrpDao;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.OrganizationUser;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.domain.UserUsrGrp;
import com.cap.bts.framework.usermgnt.service.IEmployeeInfoService;
import com.cap.bts.framework.usermgnt.service.IOrganizationMgntService;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;



/**
 * dealer user group approval service implement class
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class DealerUsrGrpApprovalServiceImpl extends BaseServiceImpl implements
    IDealerUsrGrpApprovalService {
    @Resource(name = "dealerUsrGrpApprovalDao")
    private IDealerUsrGrpApprovalDao dealerUsrGrpApprovalDao;
    @Resource(name = "organizationMgntServiceImpl")
    private IOrganizationMgntService orgMgntService;
    @Resource(name = "dealerDao")
    private IDealerDao dealerDao;
    @Resource(name = "applicationApprovalServiceImpl")
    private IApplicationApprovalService applicationApprovalService;
    @Resource(name = "userGroupDao")
    private IUserGroupDao userGroupDao;
    @Resource(name = "codeMappingImpl")
    private ICodeMapping codeMappingService;
    @Resource(name = "userMgntServiceImpl")
    private IUserMgntService userMgntService;
    @Resource(name = "approvalRuleServiceImpl")
    private IApprovalRuleService approvalRuleService;
    @Resource(name = "organizationDao")
    private IOrganizationDao organizationDao;
    @Resource(name="employeeInfoServiceImpl")
    private IEmployeeInfoService employeeInfoService;
    @Resource(name="dealerService")
    private IDealerService dealerFuncService; 
    @Resource(name="userDao")
    private IUserDao userDao;
    @Resource(name="employeeInfoDao")
    private IEmployeeInfoDao employeeInfoDao;
    @Resource(name="userUsrGrpDao")
    private IUserUsrGrpDao userUsrGrpDao;
    @Resource(name="organizationUserDao")
    private IOrganizationUserDao organizationUserDao;
    @Resource(name="applicationRuleStepDao")
    private IApplicationRuleStepDao applicationRuleStepDao;
    @Autowired
    private ISystemParaManagement sysParaMag;
    @Autowired
    IMaintainDealerEmployeeService maintainDealerEmployeeService;
    
 
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-7
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#getUserGroupApplication(com.cap.bts.gdms.dm.approval.dto.QueryApplicationDto)
     **/
    @Override
    public List<ApplicationResultDto> getUserGroupApplication(QueryApplicationDto queryDto, boolean isPaging)
        throws AppException {
        
        List<Organization> currentUserOrgs = orgMgntService.getOrganizationsByUser(queryDto.getUser());
        Organization currentUserOrg = currentUserOrgs.get(0);
        //登录人当前岗位 所在的组织的orgType是 mac
        if (currentUserOrg.getOrgType() == OrganizationType.MAC){
            queryDto.setRfsCode(currentUserOrg.getParentOrgCode());
            queryDto.setMacCode(currentUserOrg.getOrgCode()); 
        }else if (currentUserOrg.getOrgType() == OrganizationType.RFS){//登录人当前岗位 所在的组织的orgType是 rfs
            queryDto.setRfsCode(currentUserOrg.getOrgCode());
        }
        else if (currentUserOrg.getOrgType() == OrganizationType.RPC){//登录人当前岗位 所在的组织的orgType是 rpc
            queryDto.setRpcCode(currentUserOrg.getOrgCode());
        }
          
        List<UserGroupApplication> listApplication = dealerUsrGrpApprovalDao
            .getUsrGrpApprovalByDto(queryDto, isPaging);

        List<ApplicationResultDto> resultDto = new ArrayList<ApplicationResultDto>();
        for (UserGroupApplication userGroupApplication : listApplication) {
            ApplicationResultDto appResultDto = setValue(userGroupApplication);
            resultDto.add(appResultDto);
        }
        return resultDto;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-9
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#getUserGroupApplicationDetail(long)
     **/
    @Override
    public ApplicationResultDto getUserGroupApplicationDetail(long applicationId)
        throws AppException {
        UserGroupApplication usrGrpApp = dealerUsrGrpApprovalDao.findById(applicationId);
        if (usrGrpApp == null) {
            throw new AppException(CommonErrorConstants.NOT_FOUND,
                "UserGroupApplication is not found by id = " + applicationId);
        }
        ApplicationResultDto appResultDto = setValue(usrGrpApp);
        return appResultDto;
    }

    /**
     * @Date        :      Aug 30, 2011
     * @param applicationId
     * @param usrGrpApp
     * @return
     * @throws AppException
     */
    private ApplicationResultDto setValue(UserGroupApplication usrGrpApp)
        throws AppException {
        ApplicationResultDto appResultDto = new ApplicationResultDto();
        EmployeeInfo empInfo = usrGrpApp.getEmployeeInfo();
        if(empInfo!=null){
        	DealerInfo dealerInfo = dealerDao.findById(empInfo.getDealerId());
            if(dealerInfo!=null){
                List<Organization> rpcList = orgMgntService.getRPCOrgsByDealerId(dealerInfo.getId());//prc 组织
                if(rpcList!=null && rpcList.size()>0){
                    appResultDto.setRpc(rpcList.get(0).getOrgName());
                }
                appResultDto.setDealerCode(dealerInfo.getDealerCode());
                appResultDto.setDealerName(dealerInfo.getDealerName());
                appResultDto.setDealerAbbreName(dealerInfo.getDealerAbbreName());
            }
        }
        //设置申请信息
        appResultDto.setApplicationId(usrGrpApp.getId());
        appResultDto.setEmployeeId(empInfo.getId());
        appResultDto.setApprovalCatgory(usrGrpApp.getApprovalCategory());
        appResultDto.setBrandId(usrGrpApp.getBrandId());
        appResultDto.setUserCode(empInfo.getUserCode());
        appResultDto.setUserName(empInfo.getEmployeeName());
        appResultDto.setUserGroupCode(usrGrpApp.getUsrgrpCode());
        UserGroup userGroup = userGroupDao.getUserGroupByCode(usrGrpApp.getUsrgrpCode());
        //设置用户组
        if(userGroup!=null){
            appResultDto.setUserGroupName(userGroup.getUserGroupName());
        }
        if (empInfo.getGenderId() != 0) { // check non-required gender
            CodeInfoDto gender = codeMappingService.getCodeInfoDtoById(empInfo.getGenderId());
            if(gender!=null){
                appResultDto.setGender(gender.getValue());
            }
        }
        if (Utils.notNullAndZero(empInfo.getCertificateType())) { // check non-required certificate
            appResultDto.setCertificateId(empInfo.getCertificateType());
            appResultDto.setCertificateNo(empInfo.getCertificateNo());
            appResultDto.setCertificateType(codeMappingService.getCodeInfoDtoById(
                empInfo.getCertificateType()).getValue());
        }
        //判断雇佣人状态
        if (Utils.notNullAndZero(empInfo.getEmploymentStatusId())) { // check non-required
            // employment status
            appResultDto.setEmploymentStatus(CodeTextUtils.getText("Employee.WorkStatus", empInfo.getEmploymentStatusId()));
//            appResultDto.setEmploymentStatus(codeMappingService.getCodeInfoDtoById(
//                empInfo.getEmploymentStatusId()).getValue());
        }
        if (Utils.notNullAndZero(empInfo.getMarriageId())) { // check non-required marriage
            appResultDto.setMarriage(codeMappingService.getCodeInfoDtoById(
                empInfo.getMarriageId()).getValue());
        }
        if (Utils.notNullAndZero(empInfo.getEducationId())) { // check non-required education
            CodeInfoDto education = codeMappingService.getCodeInfoDtoById(empInfo.getEducationId());
            if(education!=null){
                appResultDto.setEducation(education.getValue());
            }
        }
        //sBrandTraining 转换 
        if(empInfo.getIsBrandTraining() != null){
            appResultDto.setIsBrandTraining(CodeTextUtils.getText("EmployeeInfo.yesOrNo", empInfo.getIsBrandTraining()+""));
        }
        //xportData 转换 
        if(empInfo.getExportData() != null){
            appResultDto.setExportdData(CodeTextUtils.getText("EmployeeInfo.ExportData", empInfo.getExportData()+""));
        }
        //HasDriverLicense 转换 
        if(empInfo.getHasDriverLicense() != null){
            appResultDto.setHasDriverLicense(CodeTextUtils.getText("EmployeeInfo.yesOrNo", empInfo.getHasDriverLicense()+""));
        }
        appResultDto.setPassTrainingDate(empInfo.getPassTrainingDate());
        appResultDto.setOnboardDate(empInfo.getOnboardDate());
        appResultDto.setBrandFirstServiceDate(empInfo.getBrandFirstServiceDate());
        appResultDto.setBirthDate(empInfo.getBirthDate());
        appResultDto.setBirthPlace(empInfo.getBirthPlace());
        appResultDto.setMobilePhone(empInfo.getMobilePhone());
        appResultDto.setEmail(empInfo.getEmail());
        appResultDto.setAddress(empInfo.getAddress());
        appResultDto.setPhotoUrl(empInfo.getPhotoUrl());
        appResultDto.setOperationType(CodeTextUtils.getText("UserGroupApplication.OperationType",
            String.valueOf(usrGrpApp.getOperationType())));
        Map<Integer, String> macAndRfsName = getMacAndRfsNameByDealerOrgId(usrGrpApp
            .getDealerOrgId());
        appResultDto.setMacName(macAndRfsName.get(OrganizationType.MAC));
        appResultDto.setRfsName(macAndRfsName.get(OrganizationType.RFS));
        //appResultDto.setStep(usrGrpApp.getNextStep());
        appResultDto = setApproveResultByAppId(usrGrpApp.getId(), empInfo.getBrandId(), appResultDto);
        //新增原岗位信息
        if(StringUtils.isNotBlank(usrGrpApp.getSrcGrpCode())){
        	appResultDto.setSrcGrpCode(usrGrpApp.getSrcGrpCode());
        	 UserGroup srcUserGroup = userGroupDao.getUserGroupByCode(usrGrpApp.getSrcGrpCode());
        	 if(srcUserGroup!=null){
        		 appResultDto.setSrcGrpName(srcUserGroup.getUserGroupName());
        	 }
        }
        return appResultDto;
    }

    /**
     * get mac and rfs name by dealer organization id
     * 
     * @Date : 2011-6-9
     * @param dealerOrgId
     *            dealer organization id
     * @return the macAndRfsName map
     * @throws AppException
     */
    private Map<Integer, String> getMacAndRfsNameByDealerOrgId(long dealerOrgId)
        throws AppException {
        StringBuilder macName = new StringBuilder();
        String rfsOrgCode = null;
        List<Organization> macOrRpcOrgList = orgMgntService.getSGMOrgsByDealerOrgId(dealerOrgId);
        Organization macOrg;
        Map<Integer, String> macAndRfsName = new HashMap<Integer, String>();
        if(macOrRpcOrgList!=null && macOrRpcOrgList.size()>0){
            for (int i = 0, len = macOrRpcOrgList.size(); i < len; i++) {
                macOrg = macOrRpcOrgList.get(i);
                if (macOrg.getOrgType() == OrganizationType.MAC) { // filter rpc org
                    macName.append(macOrg.getOrgName()).append(",");
                    rfsOrgCode = macOrg.getParentOrgCode();
                }
            }
            int macNameLen = macName.length();
            macName.delete(macNameLen - 1, macNameLen);
            macAndRfsName.put(OrganizationType.MAC, macName.toString());
        }
        Organization rfsOrgInfo = orgMgntService.getOrganizationByOrgCode(rfsOrgCode);
        if(rfsOrgInfo!=null){
            macAndRfsName.put(OrganizationType.RFS, rfsOrgInfo.getOrgName());
        }
        return macAndRfsName;
    }
    
    /**
     * set approve result by application id
     * 
     * @Date : 2011-6-9
     * @param appId
     *            application id
     * @param brandId
     *            brand id
     * @param appResultDto
     *            application result dto
     * @return the appResultDto
     * @throws AppException
     *             the appException
     */
    private ApplicationResultDto setApproveResultByAppId(long appId, long brandId,
        ApplicationResultDto appResultDto) throws AppException {
        List<ApplicationApproval> usrGrpApprovalList = applicationApprovalService
            .getApprovalByAppIdAndType(appId, ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE);
        UserGroup usrGrp;
        Map<String,String> approvalResultMap = CodeTextUtils.getStatusMap("App.Approval.Result");
        // approval
        for (ApplicationApproval usrGrpApproval : usrGrpApprovalList) {
            usrGrp = userGroupDao.findById(usrGrpApproval.getApproverUserGroup());
            // sales cad
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.SALESDIRECTOR.getValue())
                && brandId == BrandConstants.BRAND3) {
                appResultDto.setSalesDirectorResultCAD(usrGrpApproval.getApproverResult());
                appResultDto.setSalesDirectorApproveTimeCAD(usrGrpApproval.getApproverTime());
                appResultDto.setSalesDirectorApproveNameCAD(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setSalesDirectorResultStrCAD(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // sales che
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.SALESDIRECTOR.getValue())
                && brandId == BrandConstants.BRAND2) {
                appResultDto.setSalesDirectorResultCHE(usrGrpApproval.getApproverResult());
                appResultDto.setSalesDirectorApproveTimeCHE(usrGrpApproval.getApproverTime());
                appResultDto.setSalesDirectorApproveNameCHE(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setSalesDirectorResultStrCHE(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // rfs，cad
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.RFSCODE.getValue())
                && brandId == BrandConstants.BRAND3) {
                appResultDto.setRfsApproveResultCAD(usrGrpApproval.getApproverResult());
                appResultDto.setRfsApproveTimeCAD(usrGrpApproval.getApproverTime());
                appResultDto.setRfsApproveNameCAD(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setRfsApproveResultStrCAD(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // rfs，BUI
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.RFSCODE.getValue())
                && brandId == BrandConstants.BRAND1) {
                appResultDto.setRfsApproveResultBUI(usrGrpApproval.getApproverResult());
                appResultDto.setRfsApproveTimeBUI(usrGrpApproval.getApproverTime());
                appResultDto.setRfsApproveNameBUI(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setRfsApproveResultStrBUI(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            
            //BUI,REGION_MANAGER
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.REGION_MANAGER.getValue())
                    && brandId == BrandConstants.BRAND1) {
                    appResultDto.setRmApproveResult(usrGrpApproval.getApproverResult());
                    appResultDto.setRmApproveTime(usrGrpApproval.getApproverTime());
                    appResultDto.setRmApproveName(userMgntService.getUserByUserId(
                        usrGrpApproval.getApproverUserId()).getName());
                    appResultDto.setRmApproveResultStr(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
             }
            // rfs，CHE
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.RFSCODE.getValue())
                && brandId == BrandConstants.BRAND2) {
                appResultDto.setRfsApproveResultCHE(usrGrpApproval.getApproverResult());
                appResultDto.setRfsApproveTimeCHE(usrGrpApproval.getApproverTime());
                appResultDto.setRfsApproveNameCHE(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setRfsApproveResultStrCHE(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // mac
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.MACCODE.getValue())) {
                appResultDto.setMacApproveResult(usrGrpApproval.getApproverResult());
                appResultDto.setMacApproveTime(usrGrpApproval.getApproverTime());
                appResultDto.setMacApproveName(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setMacApproveResultStr(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // rpc
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.RPCCODE.getValue())) {
                appResultDto.setRpcApproveResult(usrGrpApproval.getApproverResult());
                appResultDto.setRpcApproveTime(usrGrpApproval.getApproverTime());
                appResultDto.setRpcApproveName(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setRpcApproveResultStr(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // after sales,che
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.AFTERSALESDIRECTOR.getValue())
                && brandId == BrandConstants.BRAND2) {
                appResultDto.setAfterSalesDirectorResultCHE(usrGrpApproval.getApproverResult());
                appResultDto.setAfterSalesDirectorApproveTimeCHE(usrGrpApproval.getApproverTime());
                appResultDto.setAfterSalesDirectorApproveNameCHE(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setAfterSalesDirectorResultStrCHE(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // branch bui
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.BRANCHDEVMGR.getValue())
                && brandId == BrandConstants.BRAND1) {
                appResultDto.setBranchDevMgrResultBUI(usrGrpApproval.getApproverResult());
                appResultDto.setBranchDevMgrApproveTimeBUI(usrGrpApproval.getApproverTime());
                appResultDto.setBranchDevMgrApproveNameBUI(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setBranchDevMgrResultStrBUI(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
            // branch cad
            if (usrGrp.getUserGroupCode().equals(UserGroupCode.BRANCHDEVMGR.getValue())
                && brandId == BrandConstants.BRAND3) {
                appResultDto.setBranchDevMgrResultCAD(usrGrpApproval.getApproverResult());
                appResultDto.setBranchDevMgrApproveTimeCAD(usrGrpApproval.getApproverTime());
                appResultDto.setBranchDevMgrApproveNameCAD(userMgntService.getUserByUserId(
                    usrGrpApproval.getApproverUserId()).getName());
                appResultDto.setBranchDevMgrResultStrCAD(approvalResultMap.get(usrGrpApproval.getApproverResult() + ""));
            }
        }
        return appResultDto;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @throws AppException
     * @Date : 2011-6-14
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#approveUserGroupApplication(com.cap.bts.gdms.dm.approval.dto.ApprovalSubmitDto)
     **/
    @Override
    public void approveUserGroupApplication(ApprovalSubmitDto submitDto) throws AppException {      
        UserGroupApplication application = dealerUsrGrpApprovalDao.findById(submitDto.getApplicationId());//取申请记彿
        if (!applicationApprovalService.saveApproval(submitDto.getApplicationId(), submitDto.getLoginId(), submitDto.getUserGroupId(), 
            submitDto.getIsApproved(), submitDto.getRemark(), ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE, submitDto.getApproverOrgId(), submitDto.getStepCode())) {
            return;
        }
        approvalRuleService.approveApplicationApproval(application, submitDto.getApplicationId(), 
            ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE, submitDto.getIsApproved(), submitDto.getStepCode());
        dealerUsrGrpApprovalDao.update(application);
        if(Utils.notNullAndZero(submitDto.getIsTransferUser())){
            transferUserDate(submitDto.getOldEmpUserCode(), submitDto.getNewEmpUserCode(), submitDto.getIsTransferUser());
        }
        //审批结束
        if(application.getState()==ApplicationState.END){
            if (ApprovalResult.APPROVAL_DISAGREE != submitDto.getIsApproved()) {
               // createUserAccountToGDMS(application, submitDto.getLoginId(), submitDto.getIsApproved());
            	//
            	UserAccountApprovalDto dto=new UserAccountApprovalDto();
        		dto.setUserCode(application.getEmployeeInfo().getUserCode());
        		dto.setUserGroupCode(application.getUsrgrpCode());
        		dto.setAppResult(submitDto.getIsApproved());
        		dto.setOrgCode(application.getOrgCode());
        		//dto.setEmploymentStatus(submitDto.getEmploymentStatus());
            	maintainDealerEmployeeService.syncEmployeeByApprovalResult(dto, 1);
            }
        }
        // RETURN TO CHANGE
        if(submitDto.getIsApproved()==ApprovalResult.APPROVAL_DISAGREE){
            //createUserAccountToGDMS(application, submitDto.getLoginId(), submitDto.getIsApproved());
            if(application.getOperationType()==EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_ADD){//如果是新增用户的驳回删除申请表人员和用户表
                User user = userDao.getUserByUserCode(application.getEmployeeInfo().getUserCode());
                //dealerUsrGrpApprovalDao.remove(application);
               // userDao.remove(user);
                EmployeeInfo employee = application.getEmployeeInfo();
                employee.setEmploymentStatusId(new Long(EmployeeStatus.DRAFT));
                employeeInfoDao.update(employee);
            } else if (application.getOperationType()==EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_UPDATE) {
            	EmployeeInfo employee = application.getEmployeeInfo();
                employee.setEmploymentStatusId(new Long(EmployeeStatus.NORMAL));
                employeeInfoDao.update(employee);
            }
        }
    }
    



    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2011-6-15
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#createUserAccountToGDMS(com.cap.bts.gdms.dm.approval.domain.UserGroupApplication)
     **/
    @Override
    public void createUserAccountToGDMS(UserGroupApplication application,Long createBy,int appResult)throws AppException {
        if(appResult==ApprovalResult.APPROVAL_AGREE){
            UserGroup userGroup = userGroupDao.getUserGroupByCode(application.getUsrgrpCode());//取用户组
            Organization organization = organizationDao.getOrganizationByOrgCode(application.getOrgCode());
            User user = userDao.getUserByUserCode(application.getEmployeeInfo().getUserCode()); //取申请人
            EmployeeInfo employee = employeeInfoDao.findById(application.getEmployeeInfo().getId());
            //设置 创建账号信息
            userUsrGrpDao.deleteUserUsrGrpByUsrCode(user.getUserCode());
            UserUsrGrp userUsrGrp = new UserUsrGrp();
            userUsrGrp.setUserId(user.getId());
            userUsrGrp.setUserGroupId(userGroup.getId());
            userUsrGrp.setCreateBy(createBy);
            userUsrGrp.setCreateDate(new Date());
            userUsrGrpDao.save(userUsrGrp);
            
            organizationUserDao.deleteOrganizationUserByUserCode(user.getUserCode());
            OrganizationUser organizationUser = new OrganizationUser();
            organizationUser.setUserId(user.getId());
            organizationUser.setOrganizationId(organization.getId());
            organizationUser.setOrganizationId(organization.getId());
            organizationUser.setCreateBy(createBy);
            organizationUser.setCreateDate(new Date());
            organizationUserDao.save(organizationUser);
            
            
            /*
             * Delete and Add user role
             */
            int isDefaultRole = 1;
            userMgntService.deleteUserRolesByUserCodeAndType(
                    user.getUserCode(), isDefaultRole);
            // create the new default user role
            List<Role> defaultRoles = userMgntService.getRolesByUsrGrpCode(
                userGroup.getUserGroupCode(), user.getBrandId());

            if (defaultRoles != null && defaultRoles.size() > 0) {
                for (Role role : defaultRoles) {
                    userMgntService.createUserRole(user.getUserCode(),
                            role.getRoleCode(), isDefaultRole);
                }
            }
            
            user.setStatusCode(UserStatus.ACTIVE);//设置活动状态
            user.setUserGroup(userGroup);
            userDao.update(user);
            
            employee.setEmploymentStatusId(new Long(EmployeeStatus.NORMAL));
            employee.setIsSgm(UserType.DEALER);
            employeeInfoDao.update(employee);
            
            User crateUser = userDao.findById(createBy);
            //sendMsg(application.getEmployeeInfo(), userGroup, organization,crateUser, appResult);
        }else{
           // sendMsg(application.getEmployeeInfo(), null, null,null, appResult);
        }
        
    }
    /**
     * 
     * @Date        :      Dec 22, 2011
     * @param employee
     * @param userGroup
     * @param organization
     * @param user
     * @param appResult
     * @return
     * @throws AppException
     */

    /**
     * {@inheritDoc} overridden:
     * 
     * @throws AppException
     *             AppException
     * @Date : 2011-6-27
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#transferUserDate(java.lang.String,
     *      java.lang.String, int)
     **/
    @Override
    public boolean transferUserDate(String oldUserCode, String newUserCode, int isAgreeUserTransfer)
        throws AppException {
      return true;
    }



    /**
     * 处理查询结果，用查询出来的数据完整加载页面需要的数据
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2011-6-27
     * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#getUnregisterUserApplication(com.cap.bts.gdms.dm.approval.dto.QueryApplicationDto)
    **/
    @Override
    public List<ApplicationResultDto> getUnregisterUserApplication(
        QueryApplicationDto queryApplicationDto,boolean isPaging,String dealerCodes)throws AppException {
    	return null;
    }
    /**
     * 设置mac id 字符串，仿,"分割
     * @Date        :      2012-4-6
     * @param queryApplicationDto
     */
    public static void getUnregisterMacids(QueryApplicationDto queryApplicationDto)  {
        ApplicationContext applicationContext = ApplicationContextUtil
        .getApplicationContext();
        IOrganizationMgntService orgMgntService = (IOrganizationMgntService) applicationContext.getBean("organizationMgntServiceImpl");
        StringBuilder macids=new StringBuilder();
        if(queryApplicationDto.getMacid()!=null && queryApplicationDto.getMacid()>0){//mac则只霿Ơ设置丿ت
            macids.append(queryApplicationDto.getMacid());
        }else{
            if(StringUtils.isNotBlank(queryApplicationDto.getOrgCode())){//区域总经理或者销售副总的子mac节点
                List<Organization> macList=orgMgntService.getChildOrganizationsByOrgCode(queryApplicationDto.getOrgCode(), OrganizationType.MAC);
                for (Iterator<Organization> iterator = macList.iterator(); iterator.hasNext();) {//拼接字符丿
                    Organization organization = (Organization) iterator.next();
                    macids.append(organization.getId());
                    if(iterator.hasNext()){//分隔
                        macids.append(",");
                    }
                }
            }else{
                if(!queryApplicationDto.isBranchDevMgr()){//如果也不是网开高级经理，则属于非法访闿
                    macids.append("-1");
                }
            }
        }
        queryApplicationDto.setMacids(macids.toString());
    }





   /**
    *  
    * {@inheritDoc} 
    * overridden:
    * @Date        :      Nov 17, 2011
    * @see com.cap.bts.gdms.dm.approval.service.IDealerUsrGrpApprovalService#getUnregisterUser(java.lang.Long)
   *
    */

}
